package com.example.controller;

import com.example.entity.User;
import com.example.service.PostService;
import com.example.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 演示控制器
 * 展示 Retrofit 的各种功能特性
 * 
 * @author example
 * @since 2024-01-01
 */
@Slf4j
@RestController
@RequestMapping("/demo")
@RequiredArgsConstructor
public class DemoController {

    private final UserService userService;
    private final PostService postService;

    /**
     * 演示所有功能
     */
    @GetMapping("/all")
    public ResponseEntity<Map<String, Object>> demonstrateAllFeatures() {
        log.info("=== 开始演示 Retrofit 所有功能 ===");
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 1. 基本 GET 请求
            log.info("1. 演示基本 GET 请求");
            List<User> users = userService.getAllUsers();
            result.put("basic_get", "获取到 " + users.size() + " 个用户");
            
            // 2. 路径参数
            log.info("2. 演示路径参数");
            User user = userService.getUserById(1L);
            result.put("path_param", user != null ? "成功获取用户: " + user.getName() : "获取用户失败");
            
            // 3. 异步请求
            log.info("3. 演示异步请求");
            User asyncUser = userService.getUserByIdAsync(2L);
            result.put("async_request", asyncUser != null ? "异步获取用户成功: " + asyncUser.getName() : "异步获取用户失败");
            
            // 4. 查询参数
            log.info("4. 演示查询参数");
            List<User> searchUsers = userService.searchUsers("Leanne Graham", null);
            result.put("query_param", "搜索到 " + searchUsers.size() + " 个用户");
            
            // 5. Map 查询参数
            log.info("5. 演示 Map 查询参数");
            Map<String, Object> searchParams = new HashMap<>();
            searchParams.put("name", "Leanne Graham");
            List<User> mapSearchUsers = userService.searchUsersWithMap(searchParams);
            result.put("map_query_param", "Map搜索到 " + mapSearchUsers.size() + " 个用户");
            
            // 6. 自定义 Header
            log.info("6. 演示自定义 Header");
            User authUser = userService.getUserWithAuth(1L, "demo_token");
            result.put("custom_header", authUser != null ? "带认证获取用户成功: " + authUser.getName() : "带认证获取用户失败");
            
            // 7. 重试机制
            log.info("7. 演示重试机制");
            User retryUser = userService.getUserWithRetry(1L);
            result.put("retry_mechanism", retryUser != null ? "重试获取用户成功: " + retryUser.getName() : "重试获取用户失败");
            
            // 8. 自定义拦截器（带签名）
            log.info("8. 演示自定义拦截器（带签名）");
            List<User> signUsers = userService.getUsersWithSign();
            result.put("custom_interceptor", "带签名获取到 " + signUsers.size() + " 个用户");
            
            // 9. POST 请求
            log.info("9. 演示 POST 请求");
            User newUser = new User();
            newUser.setName("测试用户");
            newUser.setUsername("test_user");
            newUser.setEmail("test@example.com");
            User createdUser = userService.createUser(newUser);
            result.put("post_request", createdUser != null ? "创建用户成功: " + createdUser.getName() : "创建用户失败");
            
            // 10. PUT 请求
            log.info("10. 演示 PUT 请求");
            if (createdUser != null) {
                createdUser.setName("更新后的用户");
                User updatedUser = userService.updateUser(createdUser.getId(), createdUser);
                result.put("put_request", updatedUser != null ? "更新用户成功: " + updatedUser.getName() : "更新用户失败");
            }
            
            // 11. DELETE 请求
            log.info("11. 演示 DELETE 请求");
            if (createdUser != null) {
                boolean deleted = userService.deleteUser(createdUser.getId());
                result.put("delete_request", deleted ? "删除用户成功" : "删除用户失败");
            }
            
            // 12. 表单提交
            log.info("12. 演示表单提交");
            var formPost = postService.createPostWithForm(1L, "表单标题", "表单内容");
            result.put("form_submit", formPost != null ? "表单创建文章成功: " + formPost.getTitle() : "表单创建文章失败");
            
            result.put("demo_status", "所有功能演示完成");
            
        } catch (Exception e) {
            log.error("演示过程中发生异常", e);
            result.put("error", "演示过程中发生异常: " + e.getMessage());
        }
        
        log.info("=== Retrofit 功能演示完成 ===");
        return ResponseEntity.ok(result);
    }

    /**
     * 演示基本功能
     */
    @GetMapping("/basic")
    public ResponseEntity<Map<String, Object>> demonstrateBasicFeatures() {
        log.info("=== 演示基本功能 ===");
        
        Map<String, Object> result = new HashMap<>();
        
        // GET 请求
        List<User> users = userService.getAllUsers();
        result.put("users_count", users.size());
        
        // 路径参数
        User user = userService.getUserById(1L);
        result.put("user_name", user != null ? user.getName() : "未找到用户");
        
        // 查询参数
        List<User> searchResults = userService.searchUsers("Leanne Graham", null);
        result.put("search_results", searchResults.size());
        
        return ResponseEntity.ok(result);
    }

    /**
     * 演示高级功能
     */
    @GetMapping("/advanced")
    public ResponseEntity<Map<String, Object>> demonstrateAdvancedFeatures() {
        log.info("=== 演示高级功能 ===");
        
        Map<String, Object> result = new HashMap<>();
        
        // 异步请求
        User asyncUser = userService.getUserByIdAsync(1L);
        result.put("async_user", asyncUser != null ? asyncUser.getName() : "异步请求失败");
        
        // 带签名的请求
        List<User> signUsers = userService.getUsersWithSign();
        result.put("sign_users_count", signUsers.size());
        
        // 重试机制
        User retryUser = userService.getUserWithRetry(1L);
        result.put("retry_user", retryUser != null ? retryUser.getName() : "重试请求失败");
        
        return ResponseEntity.ok(result);
    }

    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> health = new HashMap<>();
        health.put("status", "UP");
        health.put("timestamp", System.currentTimeMillis());
        health.put("service", "SpringBoot Retrofit Demo");
        health.put("version", "1.0.0");
        
        return ResponseEntity.ok(health);
    }
} 